package gui.typeEditors;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;

public class EnumEditor<T extends Enum<T>> extends TypeEditor<T> implements ActionListener
	{
	static final long serialVersionUID = 2704835030524222876L;
	
	JComboBox<T> box;
	T value;
	boolean ignoreEvents = false;
	Color origcolor;
	
	public EnumEditor(T initialValue)
		{
		super();
		
		box = new JComboBox<T>((T[]) initialValue.getDeclaringClass().getEnumConstants());
		origcolor = box.getBackground();
		doNotFireEvents = true;
		setValue(initialValue);
		doNotFireEvents = false;
		add(box);
		box.addActionListener(this);
		}

	private void setValue(T val, boolean fire)
		{
		if(val == null)
			throw new IllegalArgumentException("This enum cannot be null");
		T pVal = value;
		value = val;
		ignoreEvents = true;
		box.setSelectedItem(val);
		ignoreEvents = false;
		if(fire && pVal != value)
			{
			fireActionEvents();
			flash(Color.GREEN);
			}
		}

	@Override
	public void actionPerformed(ActionEvent e)
		{
		if(!ignoreEvents)
			parseValue();
		}

	private void parseValue()
		{
		try {
			setValue(box.getItemAt(box.getSelectedIndex()), true);
			}
		catch(IllegalArgumentException e)
			{
			flash(Color.RED);
			setValue(box.getItemAt(0));
			}
		}

	synchronized void color(Color color)
		{
		box.setBackground(color);
		}

	private void flash(Color color)
		{
		color(color);
		flashThread(new Runnable(){public void run(){color(origcolor);}}, 33);
		}

	@Override
	public T getValue()
		{
		return (T)value;
		}
	
	@Override
	public void setValue(T val)
		{
		setValue(val, false);
		}
	
	@Override
	public void setToolTipTextToSubComponents(String text)
		{
		box.setToolTipText(text);
		}

	@Override
	public void setSubComponentsEnabled(boolean en)
		{
		box.setEnabled(en);
		}
	}
